package com.cn.qtms.service;

import com.cn.qtms.common.result.ErrorCode;
import com.cn.qtms.exception.AppException;
import com.cn.qtms.feign.SysService;
import com.cn.qtms.model.JwtUser;
import com.cn.qtms.entity.vo.sys.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(readOnly = true)
/**
 * 用户名密码登陆逻辑
 * @author User
 */
public class JpaUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysService sysService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        final User user = sysService.findByUserName(username);
        //判断用户是否存在
        if (user == null) {
            throw new UsernameNotFoundException("Username [" + username + "] user not found.");
        }
        final List<String> roles = user.getRoles();
        //判断角色可用性
        if(roles==null || roles.size()==0){
            throw new AppException(ErrorCode.ACCESS_DENIED.getMessage());
        }
        return new JwtUser(user,roles);
    }
}
